package com.hp.activiti.config;

import java.io.InputStream;
import java.util.Properties;

import javax.persistence.EntityManagerFactory;

import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

/**
 * 配置数据源链接
 */
@Configuration
@EnableJpaRepositories(basePackages="com.hp.activiti.repository", entityManagerFactoryRef="wcEntityManagerFactory", transactionManagerRef="wcTransactionManager")
public class DataSourceConfig {

	/**
	 * 数据源
	 */
	@Primary 
	@Bean(destroyMethod="close")
	public DruidDataSource dataSource() throws Exception {
		InputStream is = null;
		Properties props = null;
		
		try {
			is = this.getClass().getClassLoader().getResourceAsStream("datasource.properties");
			props = new Properties();
			props.load(is);
		} finally {
			if (is != null) is.close();
		}
		
		DruidDataSource ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(props);
		return ds;
	}

	/** 
	 * jpa配置
	 */
	@Bean
	public EntityManagerFactory wcEntityManagerFactory() throws Exception {
		LocalContainerEntityManagerFactoryBean fb = new LocalContainerEntityManagerFactoryBean();
		fb.setDataSource(dataSource());
		
		HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
		jpaVendorAdapter.setGenerateDdl(false);
		jpaVendorAdapter.setShowSql(false);
		jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect");
		fb.setJpaVendorAdapter(jpaVendorAdapter);
		fb.setPackagesToScan("com.hp.activiti.model");
		fb.setPersistenceUnitName("activitiPU");
		fb.setPersistenceProviderClass(HibernatePersistenceProvider.class);		
		fb.afterPropertiesSet();
		
		return fb.getObject();
	}
	
	@Bean
	public JpaTransactionManager wcTransactionManager() throws Exception {
		JpaTransactionManager tm = new JpaTransactionManager();
		tm.setEntityManagerFactory(wcEntityManagerFactory());
		tm.afterPropertiesSet();
		return tm;
	}
	
	@Bean
	public JdbcTemplate template() throws Exception{
		return new JdbcTemplate(this.dataSource());
	}
	
	@Bean
	public PasswordEncoder passwordEncoder() {
	   return new BCryptPasswordEncoder();
	}
	
}
